import React from "react"
import Taro from "@tarojs/taro"
import { Sticky } from "@taroify/core"
import { ArrowRight } from "@taroify/icons"
import GpContainer from "@/components/GpContainer"
import { ScrollView, Text, Navigator, Image, RichText, View } from "@tarojs/components"
import GpColumnArticle from "@/components/GpColumnArticle"
import GpJumpNavs from "@/components/GpJumpNavs"
import GpCurrentPort from "@/components/GpCurrentPort"
import GpTabbar from "@/components/GpTabbar"
import clsx from "clsx"
import { pageMapper, PagePath } from "@/constants/pageMap"
import { makePagePath, navigation } from "@/utils/router"
import { cloneDeep, setPageMeta } from "@/utils/common"
import { getExamColumn, getExamArticleMenu, filterExamArticle } from "@/apis/index"
import styles from "./index.module.scss"

const ports = [{ text: "艺考专题" }]
const arrowSize = Taro.pxTransform(24)
enum ITabSwitchKey {
  /** 艺考百科 */
  wiki = 0,
  /** 专题文章 */
  article = 1
}
type ITabSwitch = {
  text: string
  value: ITabSwitchKey
  link: PagePath
}
const tabSwitchMap: ITabSwitch[] = [
  { text: "艺考百科", value: ITabSwitchKey.wiki, link: pageMapper.column },
  { text: "专题文章", value: ITabSwitchKey.article, link: pageMapper.columnArticle }
]
const selectorPrefix = "sel_"
type IWikiScroll = {
  text: string
  selector: string
  scrollTop: number
}
type IArticleScroll = IOption[]
type IState = {
  curTabSwitch: ITabSwitchKey
  tabSwitches: ITabSwitch[]
  curWikiScroll: string
  wikiScrolls: IWikiScroll[]
  content: IApiRelative.IGetExamColumn.IContent[]
  articleScrolls: IArticleScroll
  curArticleScroll: number
  /** 专题文章列表 */
  articleList: any[]
}
type IData = {
  switchKey?: ITabSwitchKey
  wikiTriggered: boolean
  handleScrollTriggered: boolean
  wikiStickyHeight: number
}
/** 艺考专题 */
class ColumnPage extends React.Component<unknown, IState> {
  extData: IData
  constructor(props) {
    super(props)
    this.state = {
      curTabSwitch: ITabSwitchKey.wiki,
      tabSwitches: tabSwitchMap,
      curWikiScroll: "",
      wikiScrolls: [],
      content: [],
      articleScrolls: [],
      curArticleScroll: 0,
      articleList: []
    }
    this.extData = {
      wikiTriggered: false,
      handleScrollTriggered: false,
      wikiStickyHeight: 0
    }
  }
  onShareAppMessage() {}
  onLoad(options: Recordable) {
    // query: { sk: 0 | 1 }
    if (typeof options.sk !== "undefined") {
      const curTabSwitch = Number(options.sk)
      this.setState({
        curTabSwitch
      })
      this.extData.switchKey = curTabSwitch
    }
    this.getMenuData()
  }
  componentDidShow() {
    this.setPageInfo()
  }
  setPageInfo = () => {
    setPageMeta({
      keywords: "艺考百科，艺考报考流程，艺考报名时间",
      title: "艺考百科知识-艺考知识大全-择艺宝",
      description:
        "择艺宝为你整理艺考学习包括过程中的全部知识点，主要包含简介、报考流程、报考时间、报名方式、报考费用以及各类艺考专业相关专题大全。"
    })
  }
  getMenuData = () => {
    getExamArticleMenu().then(res => {
      if (res.data.success) {
        const retData = res.data.data
        const menu = retData.menus || []
        let curArticleScroll = -9999
        const articleScrolls: IArticleScroll = menu.map(l => {
          if (l.selected) {
            curArticleScroll = l.id
          }
          return {
            value: l.id,
            text: l.name,
            checked: l.selected
          }
        })
        // fallback
        if (curArticleScroll === -9999 && articleScrolls.length > 0) {
          curArticleScroll = articleScrolls[0].value
        }
        this.setState({
          articleScrolls,
          curArticleScroll,
          articleList: retData.items
        })
      }
    })
  }
  handleArticleScrollChange = (item: IArticleScroll[number]) => {
    const { curArticleScroll } = this.state
    if (curArticleScroll !== item.value) {
      this.getArticleWithKey(item.value)
    }
  }
  getArticleWithKey = (id: number) => {
    Taro.showLoading()
    filterExamArticle(id)
      .then(res => {
        if (res.data.success) {
          this.setState({
            curArticleScroll: id,
            articleList: res.data.data
          })
        }
      })
      .finally(() => {
        Taro.hideLoading()
      })
  }
  /** 专题文章 */
  renderArticle = () => {
    const { articleScrolls, curArticleScroll, articleList } = this.state
    const len = articleList.length
    return (
      <View className="mt-20px">
        {/* 滚动锚点 */}
        {/* <Sticky>
          <View className="h-60px pb-8px bg-hex-fff pt-32px">
            <ScrollView scrollX scrollWithAnimation className="whitespace-nowrap">
              {articleScrolls.map(l => (
                <View
                  key={l.value}
                  className={clsx(styles["article-scroll-item"], {
                    [styles["active"]]: curArticleScroll === l.value
                  })}
                  onClick={() => this.handleArticleScrollChange(l)}
                >
                  {l.text}
                </View>
              ))}
            </ScrollView>
          </View>
        </Sticky> */}
        {/* 列表区 */}
        <View className="px-30px py-32px flex flex-col bg-hex-fff">
          {articleList.map((l, index) => {
            return (
              <View
                key={l.id}
                className={clsx({
                  "mb-32px": index !== len - 1
                })}
              >
                <GpColumnArticle article={l} />
              </View>
            )
          })}
        </View>
      </View>
    )
  }
  onReady() {
    const { switchKey } = this.extData
    if (typeof switchKey !== "undefined") {
      if (switchKey === ITabSwitchKey.wiki) {
        this.getColumnData()
      }
    } else {
      this.getColumnData()
    }
  }
  flushScrollTop = () => {
    const wikiScrolls = cloneDeep(this.state.wikiScrolls)
    const query = Taro.createSelectorQuery()
    console.log("wikiScrollsleng", wikiScrolls.length)
    for (let i = 0; i < wikiScrolls.length; i++) {
      query.select("#" + wikiScrolls[i].selector).boundingClientRect()
    }
    query.exec(res => {
      console.log("flushScrollTop", res)
      const wikiStickyHeight = this.extData.wikiStickyHeight
      for (let i = 0; i < res.length; i++) {
        wikiScrolls[i].scrollTop = res[i].top - wikiStickyHeight
      }
      this.setState({
        wikiScrolls
      })
      console.log("wikiScrolls---", wikiScrolls)
    })
  }
  pageScrollHandler(options: Taro.PageScrollObject) {
    if (this.extData.handleScrollTriggered) return
    const { scrollTop } = options
    const { wikiScrolls } = this.state
    let curSelect: any = null
    // wikiScrolls中的scrollTop理论上是从小到大的, 但是比较需要从大往小比
    for (let i = wikiScrolls.length - 1; i >= 0; i--) {
      const cur = wikiScrolls[i]
      if (scrollTop >= cur.scrollTop) {
        curSelect = cur.selector
        break
      }
    }
    if (curSelect !== null) {
      this.setState({
        curWikiScroll: curSelect
      })
    }
  }
  onPageScroll(options: Taro.PageScrollObject) {
    if (this.extData.handleScrollTriggered) return
    this.pageScrollHandler(options)
  }
  getSelector = (key: number) => {
    return selectorPrefix + key
  }
  getColumnData = () => {
    Taro.showLoading()
    getExamColumn()
      .then(res => {
        if (res.data.success) {
          const retData = res.data.data
          let curWikiScroll = ""
          const _wikiScrolls: IWikiScroll[] = (retData.menus || []).map(l => {
            if (l.selected) {
              curWikiScroll = this.getSelector(l.id)
            }
            return {
              text: l.name,
              selector: this.getSelector(l.id),
              scrollTop: 0
            }
          })
          // fallback
          if (curWikiScroll === "" && _wikiScrolls.length > 0) {
            curWikiScroll = _wikiScrolls[0].selector
          }
          const _content = retData.content || []
          _content.forEach(l => {
            l.selector = this.getSelector(l.menuId)
            if (l.childs) {
              l.childs.forEach(child => {
                child.url = makePagePath(pageMapper.knownDetail, { id: child.id })
              })
            }
          })
          this.setState(
            {
              wikiScrolls: _wikiScrolls,
              curWikiScroll,
              content: _content
            },
            () => {
              Taro.nextTick(() => {
                this.doLayoutComputition()
              })
            }
          )
        }
      })
      .finally(() => {
        this.extData.wikiTriggered = true
        Taro.hideLoading()
      })
  }
  doLayoutComputition = () => {
    this.getWikiStickyHeight().finally(() => {
      this.flushScrollTop()
    })
  }
  getWikiStickyHeight = () => {
    return new Promise(resolve => {
      const query = Taro.createSelectorQuery()
      query
        .select("#wiki-scroll-container")
        .boundingClientRect(res => {
          console.log("getWikiStickyTop", res.height)
          this.extData.wikiStickyHeight = res.height
          resolve(null)
        })
        .exec()
    })
  }
  /** 快捷导航 */
  renderJumpNavs = () => {
    return (
      <View className="mt-20px">
        <GpJumpNavs />
      </View>
    )
  }
  /** 顶部背景图 */
  renderBanner = () => {
    return (
      <View className="h-200px box-border w-750px relative">
        <Image
          src="https://static.91goodschool.com/UpFiles/public/yikao/image/yikaobg.png"
          className="h-200px w-750px cover-image"
        />
        <View className={clsx("cover-image", styles["banner-bg-mask"])}></View>
        <View className="yehei font-normal text-36px text-hex-fff text-center pt-37px relative z-2">
          <Text>艺考知识专题</Text>
        </View>
        <View className={clsx(styles["banner-subtitle"], "mt-25px relative z-2")}>
          <Text>精选热门艺考百科以及专题文章，为你专业解读</Text>
        </View>
        <View className={clsx(styles["banner-subtitle"], "mt-8px relative z-2")}>
          <Text>升学经验一网打尽</Text>
        </View>
      </View>
    )
  }
  handleTahSwitch = (item: ITabSwitch) => {
    if (this.state.curTabSwitch === item.value) return
    this.setState({
      curTabSwitch: item.value
    })
    if (!this.extData.wikiTriggered && item.value === ITabSwitchKey.wiki) {
      this.getColumnData()
    }
  }
  /** tab切换 */
  renderTabSwitch = () => {
    const { tabSwitches, curTabSwitch } = this.state
    const len = tabSwitches.length
    return (
      <View className="flex flex-row justify-center h-90px box-border bg-hex-fff">
        {tabSwitches.map((l, index) => (
          <View
            key={l.value}
            className={clsx(styles["tab-item"], {
              [styles["active"]]: curTabSwitch === l.value,
              "mr-150px": index !== len - 1
            })}
            onClick={() => this.handleTahSwitch(l)}
          >
            <Text>{l.text}</Text>
          </View>
        ))}
      </View>
    )
  }
  handleWikiScrollChange = (item: IWikiScroll) => {
    this.extData.handleScrollTriggered = true
    Taro.pageScrollTo({
      scrollTop: item.scrollTop,
      duration: 300
    })
    setTimeout(() => {
      this.setState({
        curWikiScroll: item.selector
      })
      console.log("this.extData.handleScrollTriggered = false")
      this.extData.handleScrollTriggered = false
    }, 600)
  }
  /** 艺考百科 */
  renderWiki = () => {
    const { curWikiScroll, wikiScrolls, content } = this.state
    const len = content.length
    return (
      <View className="mt-20px">
        {/* 滚动锚点 */}
        <Sticky>
          <View className="h-75px  box-border bg-hex-fff" id="wiki-scroll-container">
            <ScrollView scrollX scrollWithAnimation className="whitespace-nowrap">
              {wikiScrolls.map(l => (
                <View
                  key={l.selector}
                  className={clsx(styles["wiki-scroll-item"], {
                    [styles["active"]]: curWikiScroll === l.selector
                  })}
                  onClick={() => this.handleWikiScrollChange(l)}
                >
                  <Text>{l.text}</Text>
                </View>
              ))}
            </ScrollView>
          </View>
        </Sticky>
        {/* 章节内容 */}
        <View className="pr-30px pl-71px py-40px bg-hex-fff ">
          {/* 大章节item for loop*/}
          {content.map((l, i) => (
            <View
              className={clsx(styles["wiki-content"], {
                "pb-56px": i !== len - 1
              })}
              key={l.menuId}
            >
              <View className={styles["wiki-content-title"]}>
                <View className={styles["wiki-content-title-text"]} id={l.selector}>
                  <Text>{l.menuName}</Text>
                </View>
              </View>
              <View className={styles["wiki-list"]}>
                <View className={styles["wiki-line"]}></View>
                <View>
                  {/* items for loop */}
                  {l.childs &&
                    l.childs.length > 0 &&
                    l.childs.map((child, index) => (
                      <Navigator
                        hoverClass="none"
                        url={child.url}
                        className={clsx(styles["wiki-list-item"], {
                          "pb-48px": index !== l.childs.length - 1
                        })}
                        key={child.id}
                      >
                        <View className="yahei font-normal text-30px leading-40px text-hex-2c2c35 mb-12px">
                          <Text>{child.name}</Text>
                        </View>
                        {/* <View
                          className="taro_html"
                          dangerouslySetInnerHTML={{ __html: child.content }}
                        ></View> */}
                        <View className="taro_html">
                          <RichText nodes={child.content} userSelect selectable preview></RichText>
                        </View>
                        <View className="mt-32px">
                          <Text className="yahei font-normal text-24px text-hex-b8b8bf">
                            查看详情
                          </Text>
                          <ArrowRight
                            color="#b8b8bf"
                            style={{
                              fontSize: arrowSize
                            }}
                          />
                        </View>
                        {/* index */}
                        <View className={styles["index-dict"]}>
                          <View className="w-36px h-36px box-border text-center leading-36px bg-hex-1a8cff yahei font-normal text-24px text-hex-fff">
                            {index < 10 ? "0" + (index + 1) : index + 1}
                          </View>
                          <View className="flex flex-row w-36px h-8px box-border">
                            <View className={styles["wiki-dict-1"]}></View>
                            <View className={styles["wiki-dict-2"]}></View>
                          </View>
                        </View>
                      </Navigator>
                    ))}
                </View>
              </View>
            </View>
          ))}
        </View>
      </View>
    )
  }
  /** @deprecated */
  renderWikiContent = () => {
    const { content } = this.state
    return content.map(l => (
      <View className="pt-32px bg-hex-fff" key={l.menuId}>
        <View className="yahei-bold font-bold text-32px text-hex-2c2c35 mb-35px" id={l.selector}>
          {l.menuName}
        </View>
        <View className="flex flex-col">
          {/* 小章节item for loop */}
          {l.childs &&
            l.childs.length > 0 &&
            l.childs.map((child, index) => (
              <Navigator
                hoverClass="none"
                url={child.url}
                className={clsx(
                  "rounded-10px bg-hex-fff border border-solid border-hex-eee py-24px px-28px",
                  {
                    "mb-24px": index !== l.childs.length - 1
                  }
                )}
                key={child.id}
              >
                <View className="yahei font-normal text-30px text-hex-2c2c35 mb-13px">
                  {child.name}
                </View>
                {/* className="yahei font-normal text-26px text-hex-666 leading-40px" */}
                {/* <View
                  className="taro_html"
                  dangerouslySetInnerHTML={{ __html: child.content }}
                ></View> */}
                <View className="taro_html">
                  <RichText nodes={child.content} userSelect selectable preview></RichText>
                </View>
                <View className="mt-33px">
                  <Text className="yahei font-normal text-24px text-hex-b8b8bf">查看详情</Text>
                  <ArrowRight
                    color="#b8b8bf"
                    style={{
                      fontSize: arrowSize
                    }}
                  />
                </View>
              </Navigator>
            ))}
        </View>
      </View>
    ))
  }
  render(): React.ReactNode {
    const { wikiScrolls, curTabSwitch } = this.state
    if (curTabSwitch === ITabSwitchKey.wiki) {
      // 需要保证后台必须返回数据
      if (!wikiScrolls || wikiScrolls.length === 0) return null
    } else if (curTabSwitch === ITabSwitchKey.article) {
      if (!this.state.articleScrolls || this.state.articleScrolls.length === 0) return null
    }
    return (
      <GpContainer>
        <View>
          {/* 顶部背景图 */}
          {this.renderBanner()}
          {/* tab切换 */}
          {this.renderTabSwitch()}
          {curTabSwitch === ITabSwitchKey.wiki ? this.renderWiki() : this.renderArticle()}
          {/* 快捷导航 */}
          {this.renderJumpNavs()}
          {/* 当前位置 */}
          <GpCurrentPort ports={ports} />
        </View>
        {/* 底部导航 */}
        <GpTabbar type={14} />
      </GpContainer>
    )
  }
}
export default ColumnPage
